package com.wx.network.handler;

import com.wx.cache.ExposedInterfaceCache;
import com.wx.content.DataType;
import com.wx.network.codec.RpcProtocol;
import com.wx.network.handler.handlerInterface.RpcDataOperate;
import com.wx.network.mesg.Request;
import com.wx.network.mesg.Response;
import com.wx.util.SerializationUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Slf4j
public class RequestHandler  implements RpcDataOperate {

    private ApplicationContext applicationContext;

    public RequestHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    //创建线程池
    final DefaultEventExecutorGroup group = new DefaultEventExecutorGroup(5);
    /**
     * 业务处理类
     * 对于有返回值的进行异步处理
     * 对于没有返回的进行同步处理
     * @param channelHandlerContext
     * @param request
     */

    @Override
    public void handleData(ChannelHandlerContext channelHandlerContext, Request request) {
        String consumerInterface = request.getConsumerInterface();
        String methodName = request.getMethodName();
        Class[] paramTypes = request.getParamTypes();
        log.info("{}请求id是{}",request.getMethodName(),request.getRequestId());
        String consumerInterface1 = request.getConsumerInterface();
        Class aClass = ExposedInterfaceCache.getClass(consumerInterface1);
        Object bean = applicationContext.getBean(aClass);
        Method method = null;
        try {
            method = bean.getClass().getMethod(request.getMethodName(), request.getParamTypes());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Object invoke = null;
        try {
            invoke = method.invoke(bean, request.getAges());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        RpcProtocol protocol = new RpcProtocol();
        Response response = new Response();
        response.setDataType(DataType.BUSSINESS);
        response.setResult(invoke);
        response.setRequestId(request.getRequestId());
        byte[] bytes = SerializationUtil.serialzationObj(response);
        protocol.setLength(bytes.length);
        protocol.setData(bytes);
        //发送信息
        log.info("处理完毕发送的消息是{}",invoke);
        channelHandlerContext.writeAndFlush(protocol);
    }
}
